using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 帧显示, 控制帧率
    /// </summary>
    public class ShowFPSTool : MonoBehaviour
    {
        public float updateInterval = 0.5F;
        private float lastInterval;
        private int frames = 0;
        private float fps;
        public bool isFPSGUI = true;

        [Header("帧")] public int frameRate = 60;
        public FrameState state = FrameState.None;

        void Start()
        {
            //

            lastInterval = Time.realtimeSinceStartup;
            frames = 0;
        }

        void OnGUI()
        {
            if (isFPSGUI)
            {
                string text = "FPS:" + fps.ToString("f2");
                GUIStyle gs = new GUIStyle();
                gs.fontSize = 60;
                GUI.Label(new Rect(0, 100, 200, 200), text,gs);
            }
        }

        void Update()
        {
            frames++;

            if (Time.realtimeSinceStartup > lastInterval + updateInterval)
            {
                fps = frames / (Time.realtimeSinceStartup - lastInterval);
                frames = 0;
                lastInterval = Time.realtimeSinceStartup;
            }

            if (state == FrameState.Lock)
            {
                Application.targetFrameRate = frameRate;
            }
            else
            {
                Application.targetFrameRate = 100;
            }
        }

        public enum FrameState
        {
            Lock,
            None,
        }
    }
}